const keyName = "suanli-";

const getFullName = (name) => {
  return `${keyName}${name}`;
};

/**
 * 存储localStorage
 * cacheTime: 允许在添加时设置缓存时间
 */
export const setStore = ({ name, content, cacheTime = "infinite" }) => {
  if (!name || !content) return;
  const storeName = getFullName(name);
  const cacheItem = {
    content,
    dateTime: cacheTime === "infinite" ? null : +new Date() + cacheTime, // 兼容永久缓存
  };

  localStorage.setItem(storeName, JSON.stringify(cacheItem));
};

/**
 * 获取localStorage
 */
export const getStore = (name) => {
  const storeName = getFullName(name);
  let item = localStorage.getItem(storeName);
  if (!item) return null;
  item = JSON.parse(item);
  const { content, dateTime } = item;
  //  如果没有设置缓存则直接返回content
  if (!dateTime) return content;
  const now = +new Date();
  // 判断缓存是否过期
  if (now - dateTime <= 0) {
    return content;
  }
  removeStore(name);
  return null;
};

/**
 * 删除localStorage
 */
export const removeStore = (name) => {
  const storeName = getFullName(name);
  localStorage.removeItem(storeName);
};

/**
 * 清空全部localStorage
 */
export const clearStore = () => {
  localStorage.clear();
};
